package com.asia.algorithmcode.array;

/**
 * @DESCRIPTION: 74
 * @USER: wanfu
 * @DATE: 2025/3/21 星期五 17:24
 */
public class SearchMatrix {

    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        int left = 0;
        int right = m * n - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (getValue(mid, matrix, n) == target) {
                return true;
            } else if (getValue(mid, matrix, n) > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return false;
    }

    /**
     * 从位置计算行，列，取出数组中的值
     *
     * @param value
     * @param matrix
     * @return
     */
    private Integer getValue(int value, int[][] matrix, int n) {

        int row = value / n;
        int col = value % n;

        return matrix[row][col];
    }


}
